using UnityEngine;
using System.Collections.Generic;

namespace Network 
{
    public delegate void MsgCallback(MsgObject f_msg);

    public class MsgDispatcher
	{
	    private IConnection _connection;

        private Dictionary<uint, MsgCallback> _msgDispatch = new Dictionary<uint, MsgCallback>();

        public MsgDispatcher(IConnection f_connection)
	    {
	        _connection = f_connection;
	    }
	
        public void ResetConnection(IConnection f_connection)
        {
            _connection = f_connection;
        }
	    public void process(float deltaTime)
	    {
            _connection.Tick(deltaTime);
            MsgObject msg = _connection.GetMsg();

	        while (msg != null)
	        {
                DispatchMsg(msg);
                msg = _connection.GetMsg();
            }
	    }
	
	    public void RegistMsg(uint f_id, MsgCallback f_func)
	    {
            if (_msgDispatch.ContainsKey(f_id))
                _msgDispatch[f_id] += f_func;
            else
                _msgDispatch.Add(f_id, f_func);
	    }

		public void UnregistMsg(uint f_id, MsgCallback f_func)
		{
            if (_msgDispatch.ContainsKey(f_id))
            {
                if (f_func == null)
                {
                    _msgDispatch.Remove(f_id);
                }
                else
                {
                    _msgDispatch[f_id] -= f_func;
                }
            }
            else
                Debug.LogWarning("Unregist unknow Message : " + f_id.ToString());
        }

        public void DispatchMsg(MsgObject msg)
        {
            if (_msgDispatch.ContainsKey(msg.msgID))
            {
                MsgCallback fn = _msgDispatch[msg.msgID];
                fn(msg);
            }
            else
            {
                Debug.Log("Receive unknow Message : " + msg.msgID.ToString());
            }
        }
	}
}